<template>
  <div class="news-container">
    <!-- 搜索栏 -->
    <div class="search-wrapper">
      <div class="search-item">
        <span class="label">新闻标题：</span>
        <el-input v-model="searchForm.titleFuzzy" placeholder="请输入新闻标题" clearable />
      </div>
      <div class="search-item">
        <span class="label">作者：</span>
        <el-input v-model="searchForm.authorName" placeholder="请输入作者名称" clearable />
      </div>
      <div class="search-item">
        <span class="label">时间范围：</span>
        <el-date-picker
          v-model="searchForm.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </div>
      <div class="btn-group">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 新闻列表 -->
    <div class="news-list">
      <el-row :gutter="20">
        <el-col v-for="news in newsList" :key="news.id" :span="8">
          <el-card class="news-item" shadow="hover">
            <!-- 新增：新闻图片 -->
            <div class="news-image">
                <el-image
                    :src="news.imageUrl"
                    fit="fill"
                    class="activity-cover"
                    :preview-src-list="news.imageUrl ? [news.imageUrl] : []"
                    :preview-teleported="true"
                />
            </div>
            <div class="news-info">
              <div class="news-title-wrapper">
                <h4 class="news-title">{{ news.title }}</h4>
                <!-- 修改：星星 -->
                <div class="star-rating">
                  <el-rate
                    v-model="news.hot"
                    disabled
                    :show-text="false"
                    :show-score="false"
                    :max="news.hot"
                  />
                </div>
              </div>
              <div class="news-description">
                <span>{{ news.content }}</span>
              </div>
              <div class="news-details">
                <div class="news-author">
                  <span>作者: {{ news.authorName }}</span>
                </div>
                <div class="news-time">
                  <span>发布时间: {{ news.createdAt }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const newsList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)

const searchForm = reactive({
  titleFuzzy: '',
  authorName: '',
  timeRange: [],
  orderBy: 'created_at desc'
})

// 获取新闻列表
const loadNews = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      titleFuzzy: searchForm.titleFuzzy,
      authorName: searchForm.authorName,
      orderBy: searchForm.orderBy,
      status: 1
    }

    // 修改：将 timeRange 映射为 createdAtStart 和 createdAtEnd
    if (searchForm.timeRange && searchForm.timeRange.length === 2) {
      params.createdAtStart = searchForm.timeRange[0]
      params.createdAtEnd = searchForm.timeRange[1]
    }

    const res = await axios.get('/news/loadDataList', {
      params
    })

    console.log('API响应:', res.data)

    if (res.data.status === 'success') {
      const responseData = res.data.data
      if (responseData && responseData.list) {
        newsList.value = responseData.list
        total.value = responseData.totalCount
      }
    } else {
      ElMessage.error(res.data.info || '获取新闻列表失败')
      newsList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取新闻列表失败:', error)
    ElMessage.error('获取新闻列表失败')
    newsList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const isNewNews = (createdAt) => {
  return dayjs().diff(dayjs(createdAt), 'day') <= 3
}

const handleSearch = () => {
  currentPage.value = 1
  loadNews()
}

const resetSearch = () => {
  searchForm.titleFuzzy = ''
  searchForm.authorName = ''
  searchForm.timeRange = []
  searchForm.orderBy = 'created_at desc'
  currentPage.value = 1
  loadNews()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadNews()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadNews()
}

onMounted(() => {
  loadNews()
})
</script>

<style scoped>
.news-container {
  padding: 20px;
}

.search-wrapper {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.search-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  margin-right: 10px;
  white-space: nowrap;
  font-weight: bold;
}

.btn-group {
  display: flex;
  gap: 10px;
}

.news-list {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.news-item {
  margin-bottom: 20px;
  transition: transform 0.2s;
}

.news-item:hover {
  transform: translateY(-5px);
}

.news-info {
  text-align: left;
  padding: 10px;
}

.news-title {
  margin: 10px 0;
  font-size: 18px;
  color: #333;
}

.news-description {
  color: #666;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.news-details {
  display: flex;
  flex-direction: column;
  margin: 10px 0;
  color: #666;
}

.news-details .news-author {
  margin-bottom: 5px;
  font-weight: bold;
}

.news-details .news-time {
  font-size: 14px;
}

/* 新增：新闻图片样式 */
.news-image {
  width: 100%;
  height: 160px;
  overflow: hidden;
  margin-bottom: 15px;
  border-radius: 8px;
}

.activity-cover  {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

/* 新增：新闻标题和热门标签的样式 */
.news-title-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.hot-tag {
  margin-left: 10px;
}

/* 新增：星星样式 */
.star-rating {
  margin-left: 10px;
  display: flex;
  align-items: center;
}

.star-count {
  margin-left: 5px;
  font-size: 14px;
  color: #ff9900;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>